package com.hm.PushCaseService.utils.md5;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.security.MessageDigest;

public class Md5Utils {
    private static final Logger logger = LoggerFactory.getLogger(Md5Utils.class);

    public static String generateMD5(String inStr) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            char[] charArray = inStr.toCharArray();
            byte[] byteArray = new byte[charArray.length];
            for (int i = 0; i < charArray.length; i++) {
                byteArray[i] = (byte) charArray[i];
            }
            byte[] md5Bytes = md5.digest(byteArray);
            StringBuilder hexValue = new StringBuilder();
            for (byte md5Byte : md5Bytes) {
                int val = ((int) md5Byte) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return "";
        }
    }


    public static String generateMD51(String input) {
        try {
            // 创建MessageDigest对象，选择MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算摘要
            md.update(input.getBytes());
            // 获取摘要字节数组
            byte[] digest = md.digest();
            // 将摘要字节数组转换为16进制字符串
            BigInteger bigInt = new BigInteger(1, digest);
            StringBuilder md5 = new StringBuilder(bigInt.toString(16));
            // 补齐前导0，确保字符串长度为32
            while (md5.length() < 32) {
                md5.insert(0, "0");
            }
            return md5.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }


}
